# 参考代码 https://blog.csdn.net/qq_45704640/article/details/131656908
from machine import Pin ,I2C
from utime import sleep
import utime


i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=100000)
#根据已有挂载i2c设备增减i2c.scan()[] 我挂载了3个就打印3个，否则报错
#print("所有I2C Address : ", i2c.scon().size()) # Display device address

class AHT20:
    def __init__(self):
        self.addr=0x38
        self.sig_getStatus=bytearray(1)
        self.sig_getStatus[0] = 0x71
        self.sig_init=bytearray(3)
        self.sig_init[0] = 0xe1
        self.sig_init[1] = 0x08
        self.sig_init[2] = 0x00
        self.sig_measure=bytearray(3)
        self.sig_measure[0] = 0xac
        self.sig_measure[1] = 0x33
        self.sig_measure[2] = 0x00
        
        self.checkDevice()
        self.initDevice()
        
    def checkDevice(self):
        devList = i2c.scan()
        while self.addr not in devList:
            print("not found devices!")
            utime.sleep_ms(1000)
    
    def initDevice(self):
        i2c.writeto(self.addr,self.sig_getStatus)
        while not (int.from_bytes(i2c.readfrom(self.addr,1),'big') & 0x18):
            i2c.writeto(self.addr,self.sig_init)
            utime.sleep_ms(100)
        
    def getData(self):
        flag = 1
        i2c.writeto(self.addr,self.sig_measure)
        d = 0
        while flag:
            utime.sleep_ms(100)
            d = i2c.readfrom(self.addr,6)
            flag = d[0] & 0x01
        else:
            humidity = int.from_bytes(bytes.fromhex('0'+d.hex()[2:7]),'big') * 100.0 / 0x100000
            temperature= int.from_bytes(bytes.fromhex('0'+d.hex()[7:12]),'big') * 200.0 / 0x100000 - 50
            return round(temperature,2),round(humidity,2)
                                    

def test():
    aht=AHT20()
    while True:
        print(aht.getData())
        utime.sleep(60)

                  